import axios from 'axios'
import qs from 'qs'
import router from '../main';
import Vue from 'vue'

axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers['X-Requested-With'] = "XMLHttpRequest";
// axios.defaults.baseURL = ajaxUrl;
axios.defaults.responseType = 'json';
// axios.defaults.withCredentials = true;

//POST传参序列化


axios.interceptors.request.use((config) => {
  if (config.method === 'post') {
    if (config.headers['Content-Type'] == 'application/x-www-form-urlencoded;charset=UTF-8') {
      config.data = qs.stringify(config.data);
    }//config.headers['Content-Type'] ='application/json;charset=UTF-8';
  }
  if (window.localStorage.getItem('lng-token')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers['lng-token'] = window.localStorage.getItem('lng-token');
    config.headers.Authorization = `token ${window.localStorage.getItem('lng-token')}`;
  }
  // console.log(JSON.stringify(config));
  return config;
}, (error) => {
  console.log("错误的传参");
  return Promise.reject(error);
});

//code状态码200判断
axios.interceptors.response.use((res) => {

  if (res.data && res.data.code == 500){
    Vue.$vux.toast.text(res.data.message);
    return false;
  }
  if (res.data && res.data.code == 403){
    Vue.$vux.toast.text(res.data.message);
    return false;
  }
  if (res.data && res.data.code == 0){
    if (res.data.data){
      Vue.$vux.toast.text(res.data.data);
    }else {
      Vue.$vux.toast.text(res.data.message);
    }
    return false;
  }
  if (res.data && res.data.code == 10104){
    Vue.$vux.toast.text(res.data.data);
    return false;
  }
  if (res.data && res.data.code == 10004){
    Vue.$vux.toast.text(res.data.message);
    return false;
  }
  if (res.data && res.data.code == 10103){
    Vue.$vux.toast.text(res.data.data);
    return false;
  }
  if (res.data && res.data.code == 10001){
    Vue.$vux.toast.text(res.data.data[0].errorMsg);
    return false;
  }

  return res;
}, (error) => {
  console.log("网络异常");

  if (error && error.response) {
    switch (parseInt(error.response.status)) {
      case 401:
        window.localStorage.removeItem("lng-token");
        setTimeout(function () {
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.name}
          });
        },1000);
        error.message = '登录过期，请重新登录';
        break;
      case 504:
        error.message = '网关超时';
        break;
      case 502:
        error.message = '后端接口未开';
        break;
      case 403:
        error.message = '当前账号没有操作权限';
        break;
    }
  } else {
    error.message = '网关超时'
  }
  return Promise.reject(error);
});

export default axios;
